package com.atcd.oss.demo1.service;

import com.aliyun.oss.model.CannedAccessControlList;
import org.springframework.stereotype.Controller;
import com.aliyun.oss.ClientException;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.OSSException;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.UUID;

@Service
public class ossService {


    public String Demo(MultipartFile multipartFile,String dir) throws  Exception {

            // Endpoint以华东1（杭州）为例，其它Region请按实际情况填写。
            String endpoint = "oss-cn-chengdu.aliyuncs.com";
            // 阿里云账号AccessKey拥有所有API的访问权限，风险很高。强烈建议您创建并使用RAM用户进行API访问或日常运维，请登录RAM控制台创建RAM用户。
            String accessKeyId = "LTAI5t6DLY7X3U6NeuUmxMYq";
            String accessKeySecret = "TJkGbb3O7AczvVAGLcKZ50TZV4CCFR";
            // 填写Bucket名称，例如examplebucket。
            String bucketName = "imgtw";


            // 创建OSSClient实例。
            OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);

            try {
                if(!ossClient.doesBucketExist(bucketName)){ //如果不存在这个桶，会自动创建
                     //创建bucket
                    ossClient.createBucket(bucketName);
                    //设置oss实例的访问权限,公共读
                    ossClient.setBucketAcl(bucketName, CannedAccessControlList.PublicRead);
                }

                //2.获取文件的流
                InputStream fileInputStream = multipartFile.getInputStream();
                //3.构建日期目录
                SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd");
                String dataPath = dateFormat.format(new Date());

                //4，开始组装我们自己定义的文件名
                String originalFilename = multipartFile.getOriginalFilename();
                String filename = UUID.randomUUID().toString();
                String suffix =originalFilename.substring(originalFilename.lastIndexOf("."));
                String newName=filename+suffix;
                //完整文件名字
                String finalNameUrl=dir+"/"+dataPath+"/"+newName;

                //以流的形式向桶里面写进去 imgtw/data/filename ....就够成了多层目录分隔
                ossClient.putObject(bucketName, finalNameUrl, fileInputStream);
                return "上传成功:网址为: http://"+bucketName+"."+endpoint+"/"+finalNameUrl;
            } catch (OSSException oe) {
                System.out.println("Caught an OSSException, which means your request made it to OSS, "
                        + "but was rejected with an error response for some reason.");
                System.out.println("Error Message:" + oe.getErrorMessage());
                System.out.println("Error Code:" + oe.getErrorCode());
                System.out.println("Request ID:" + oe.getRequestId());
                System.out.println("Host ID:" + oe.getHostId());
            } catch (ClientException ce) {
                System.out.println("Caught an ClientException, which means the client encountered "
                        + "a serious internal problem while trying to communicate with OSS, "
                        + "such as not being able to access the network.");
                System.out.println("Error Message:" + ce.getMessage());
                return "上传失败";
            } finally {
                if (ossClient != null) {
                    ossClient.shutdown();
                }
            }
            return null;
        }

}
